package com.ncmmall.mall.controller.securitys;

import com.ncmmall.application.business.merchant.MerchantApplication;
import com.ncmmall.application.securitys.user.UserApplication;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.QMerchantGoodsChannel;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.securitys.MD5HashUtils;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;

/**
 * @author likaikai
 *         系统用户管理
 */
@Controller
@RequestMapping(value = "/securitys/users")
public class InfoController {

    private final static Logger logger = LoggerFactory.getLogger(InfoController.class);

    @Value("${web.domain}")
    private String webDomain;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private UserApplication userApplication;

    @Autowired
    private MerchantApplication merchantApplication;

    /**
     * 用户信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    private String info(Model model) {

        WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class);

        List<MerchantGoodsChannel> goodsChannels = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(merchant.getId()), MerchantGoodsChannel.class);
        List<String> channelNames = Lists.transform(goodsChannels, new Function<MerchantGoodsChannel, String>() {
            @Nullable
            @Override
            public String apply(@Nullable MerchantGoodsChannel input) {
                return input.getChannel().getName();
            }
        });

        model.addAttribute("merchant", merchant).addAttribute("channels", queryChannelService.findAll(QGoodsChannel.goodsChannel.status.eq(1).and(QGoodsChannel.goodsChannel.level.eq(1).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0))), GoodsChannel.class)).addAttribute("channelNames", channelNames).addAttribute("_method", "PUT");


        return "securitys/user/info";
    }

    /**
     * 修改基础信息（昵称、姓名、头像、邮箱、手机号、公司信息）
     *
     * @param requestWith
     * @param params
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> info(@RequestHeader("X-Requested-With") String requestWith, WebUser params) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            params.setId(Securitys.currentUser().getId());
            merchantApplication.modifyMerchantInfo(params);
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[修改用户信息异常]", e);
            return ImmutableMap.of("status", false, "message", "修改用户信息失败");
        }
    }

    /**
     * 修改密码页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.GET)
    private String modifyPassword(Model model) {
        WebUser user = queryChannelService.findOne("select u from WebUser u where u.id = :id", ImmutableMap.of("id", Securitys.currentUser().getId()), WebUser.class);
        model.addAttribute("user", user).addAttribute("_method", "PUT");
        return "securitys/user/modifyPassword";
    }


    /**
     * 修改密码
     *
     * @param requestWith
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modifyPassword(@RequestHeader("X-Requested-With") String requestWith, @RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            WebUser user = queryChannelService.findOne("select u from WebUser u where u.id = :id", ImmutableMap.of("id", Securitys.currentUser().getId()), WebUser.class);
            String passwordAsMd5 = MD5HashUtils.asMD5(MD5HashUtils.MD5(oldPassword), Securitys.currentUser().getUsername());
            if (!user.getPassword().equals(passwordAsMd5)) {
                return ImmutableMap.of("status", false, "message", "原密码错误");
            }

            userApplication.modifyPassword(user, newPassword);

            Subject subject = SecurityUtils.getSubject();
            Securitys.unactivateUserSession();
            subject.logout();

            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[修改密码异常]", e);
            return ImmutableMap.of("status", false, "message", "修改密码失败");
        }
    }

}
